import type { IMasterEntity, ITreeEntity } from '@/types/entity';

export function formatDate(date: number | Date, format: string): string {
  let time: number | Date = date;
  if (typeof time === 'number') {
    time = new Date(time);
  }
  const _date = time as Date;
  const year = _date.getFullYear();
  const month = (_date.getMonth() + 1).toString().padStart(2, '0');
  const day = _date.getDate().toString().padStart(2, '0');
  const hours = _date.getHours().toString().padStart(2, '0');
  const minutes = _date.getMinutes().toString().padStart(2, '0');
  const seconds = _date.getSeconds().toString().padStart(2, '0');

  return format.replace('yyyy', year.toString()).replace('MM', month).replace('dd', day).replace('HH', hours).replace('mm', minutes).replace('ss', seconds);
}

export function dwDeepClone(data: object | undefined) {
  if (!data) {
    return data;
  }
  return JSON.parse(JSON.stringify(data));
}

export function template(str: string, dataObj: Record<string, string>) {
  str = str.replace(/#\{(\w+)\}/g, (m: string, i: string) => {
    return dataObj[i];
  });
  return str;
}

export function getIdArrayFormJsonList(jsonList: Array<IMasterEntity>) {
  const idArray: string[] = [];
  for (let i = 0; i < jsonList.length; i++) {
    idArray.push(jsonList[i].id);
  }
  return idArray;
}

export const translateDataToTree = (array: ITreeEntity[]) => {
  if (array === null) {
    return [];
  }
  const rootIds = getRootIds(array);
  //第一层数据
  const parents = array.filter((item) => rootIds.includes(item.id));
  //有父节点的数据
  const childrens = array.filter((item) => !rootIds.includes(item.id));

  function translator(parents: ITreeEntity[], childrens: ITreeEntity[]) {
    parents.forEach((parent) => {
      childrens.forEach((children, index) => {
        //找到子层的父层
        if (children.parentId === parent.id) {
          //temp 这步不是必须
          //对子节点数据进行深复制
          const temp = JSON.parse(JSON.stringify(childrens));
          //让当前子节点从temp中移除，temp作为新的子节点数据，这里是为了让递归时，子节点的遍历次数更少，如果父子关系的层级越多，越有利
          temp.splice(index, 1);
          //判断是否有children属性 有就直接push 没有就增加children属性
          // eslint-disable-next-line @typescript-eslint/no-unused-expressions
          parent.children ? parent.children.push(children) : (parent.children = [children]);
          //不用temp 传childrens也可
          translator([children], temp);
        }
      });
    });
  }
  translator(parents, childrens);
  //返回最终结果
  return parents;
};

const getRootIds = (data: ITreeEntity[]): string[] => {
  const rootIds: string[] = [];

  for (let i = 0; data && i < data.length; i++) {
    const node = data[i];
    const parentId = node.parentId;
    let isExist = false;
    for (let j = 0; j < data.length; j++) {
      const id = data[j].id;
      if (parentId === id) {
        isExist = true;
        break;
      }
    }
    if (!isExist) {
      rootIds.push(node.id);
    }
  }
  return rootIds;
};
